package per.srp.demo.carLink;


import com.alibaba.fastjson.JSONObject;
import per.srp.demo.carLink.Utils.CarInfoCodeTool;
import per.srp.demo.carLink.Utils.SocketOperation;
import per.srp.demo.carLink.entity.CarAndSocket;
import per.srp.demo.carLink.entity.CarCommand;

import java.io.IOException;
import java.net.Socket;
import java.util.LinkedList;

public class ReturnSocketHandler {
    private CarAndSocket carAndSocket;
    public ReturnSocketHandler(CarAndSocket carAndSocket) {
        this.carAndSocket = carAndSocket;
    }

    private static CarCommand[] commandToArray(LinkedList<CarCommand> carCommands){
        CarCommand[] commands = null;

        if(carCommands!=null){
            commands = new CarCommand[carCommands.size()];
            int index = 0;
            for (CarCommand eachCommand : carCommands){
                commands[index] = eachCommand;
                index++;
            }
        }
        return commands;
    }

    public void doCommand(LinkedList<CarCommand> carCommands) throws IOException {
        Socket socket = carAndSocket.getSocket();
        if(!socket.isClosed()){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",CarInfoCodeTool.randomNumbers(10));

//            LinkedList<CarCommand> commandLinkedList = new LinkedList<>();
//            commandLinkedList.add(new CarCommand("left",12,""));
//            commandLinkedList.add(new CarCommand("up",12,""));
//            commandLinkedList.add(new CarCommand("down",12,""));
//            commandLinkedList.add(new CarCommand("stop",12,""));
//
//            jsonObject.put("commands",commandToArray(commandLinkedList));
            jsonObject.put("commands",commandToArray(carCommands));
            System.out.println("返回: "+jsonObject);
            System.out.println(CarInfoCodeTool.deCodeString(CarInfoCodeTool.enCodeJSONObject(jsonObject)));
            //发送指令给小车
            SocketOperation.writeAndClose(socket,CarInfoCodeTool.enCodeJSONObject(jsonObject));
        }
    }
}
